#include <string.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<stdlib.h>

#include "data_unit.h"
#include "ipcserver.h"
#include "cmd.h"
#include "data_integrity.h"
#include "file.h"

#define IPCFILE "/tmp/ftr_ipc_test"

static int __newclient(void *handler, void *client, void *param){
    pipcserver_t pipcserver = (pipcserver_t)handler;
    pdataunit_t precv = (pdataunit_t)param;
    char filecontent[100] = {0};

    
    du_msg_t msg = {
        .param = client,
    };

    printf("new client \n");
    (void)pipcserver;
    precv->recv(precv, (unsigned char*)filecontent, sizeof(filecontent), (void*)&msg);
//    pipcserver->send(pipcserver, client, (unsigned char*)hello, strlen(hello));

    return 0;
}

int main(int argc, char **argv) {

    pcmd_t pcmd = NULL;
    pipcserver_t pipcserver = NULL;
    pdi_t pdi = NULL;
    pfile_t pfile = NULL;
    

    cmd_alloc(&pcmd);
    ipcserver_alloc(&pipcserver);
    di_alloc(&pdi, 200);
    file_alloc(&pfile);

    
    pcmd->init(pcmd);
    pipcserver->init(pipcserver, IPCFILE, NULL);    
    pipcserver->register_notify(pipcserver, __newclient, (void*)pfile);

    pfile->init(pfile, "/tmp/wifichannel", 1);
    
    du_chain_t read_chain[] = {        
        {(pdataunit_t)pipcserver, DATAUNIT_DIRECT_NONE, DATAUNIT_DIRECT_NONE},
        {(pdataunit_t)pdi, DATAUNIT_DIRECT_RECV, DATAUNIT_DIRECT_NONE},
        {(pdataunit_t)pcmd, DATAUNIT_DIRECT_RECV, DATAUNIT_DIRECT_NONE},
    };

    du_chain_t write_chain[] = {
        {(pdataunit_t)pfile, DATAUNIT_DIRECT_NONE, DATAUNIT_DIRECT_NONE},
        {(pdataunit_t)pdi, DATAUNIT_DIRECT_SEND, DATAUNIT_DIRECT_NONE},
        {(pdataunit_t)pipcserver, DATAUNIT_DIRECT_NONE, DATAUNIT_DIRECT_SEND},
    };
    
    du_chain_init(read_chain, sizeof(read_chain)/sizeof(read_chain[0]));
    du_chain_init(write_chain, sizeof(write_chain)/sizeof(write_chain[0]));


    pipcserver->loop(pipcserver);

    pcmd->deinit(pcmd);
    pipcserver->deinit(pipcserver);
    
    
    di_dealloc(&pdi);
    cmd_dealloc(&pcmd);
    ipcserver_dealloc(&pipcserver);
    return 0;
}


